﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HlELock.Core
{
    public static class ExcelExtension
    {
        static ExcelExtension()
        {
            ExcelPackage.License.SetNonCommercialPersonal("cc1027cc");
        }
        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <param name="func">参数1 当前行的值，参数2 表头</param>
        /// <returns></returns>
        public static List<T> ReadExcel<T>(this Stream stream, Func<string[], string[], int, T> func, int headerRow = 1, int sheetIndex = 0) where T : class
        {
            var package = new ExcelPackage(stream);
            var workseet = package.Workbook.Worksheets[sheetIndex];
            var rows = workseet.Dimension.Rows;
            var cols = workseet.Dimension.Columns;

            var headers = new string[cols];
            if (headerRow > 0)
            {
                for (int i = 0; i < headers.Length; i++)
                {
                    headers[i] = workseet.Cells[headerRow, i + 1].GetValue<string>();
                }
            }
            var result = new List<T>();

            for (int i = (headerRow + 1); i <= rows; i++)
            {
                var colValues = new string[cols];
                for (int j = 0; j < colValues.Length; j++)
                {
                    colValues[j] = workseet.Cells[i, j + 1].GetValue<string>();
                }

                try
                {
                    result.Add(func(colValues, headers, i));
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return result;
        }


        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="filePath"></param>
        public static void ExportToExcel<T>(this List<T> data, string filePath)
        {

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                // 将 List<T> 加载到 worksheet（自动使用属性名作为列头）
                worksheet.Cells["A1"].LoadFromCollection(data, true); // true 表示包含列头

                // 可选：优化列宽
                worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

                // 保存到文件
                File.WriteAllBytes(filePath, package.GetAsByteArray());
            }

            Console.WriteLine($"Excel 文件已生成：{filePath}");
        }

    }
}
